#============================================================
#	Json Util
#============================================================
#  Json 数据转换器
#============================================================
# @datetime: _to_0_to__to_-4-_to_0 01:50:_to_4
#============================================================

##  转换 JSON 数据
class_name JSONUtils


##  根据字典数据设置对象所有属性
static func set_property_by_dict(dict: Dictionary, object: Object) -> void:
	if dict.size() > 0 and object:
		for property in dict:
			# 对象存在这个属性则设置
			if property in object:
				object.set(property, dict[property])


##  字典转换为 Object 对象
##[br]
##[br][code]dict[/code]  字典数据
##[br][code]class_[/code]  Class类或脚本
static func dict_to_object(dict: Dictionary, class_) -> Object:
	var object = class_.new()
	set_property_by_dict(dict, object)
	return object


##  对象转换为字典
static func object_to_dict(object, all: bool = false) -> Dictionary:
	var data : Dictionary = {}
	var value
	var property_list : Array
	if not all:
		property_list = object.get_script().get_script_property_list()
	else:
		property_list = object.get_property_list()
	for prop in property_list:
		value = object.get(prop['name'])
		if value:
			data[prop['name']] = value
	return data


##  对象转为 JSON 数据
static func object_to_json(object: Object) -> String:
	var j = JSON.new()
	return j.stringify(object_to_dict(object))


##  Json 转为对象 
##[br]
##[br][code]_class[/code]  转换成的对象类型
static func json_to_object(json: String, _class) -> Object:
	var j = JSON.new()
	if j.parse(json) == OK:
		return dict_to_object(j.get_data(), _class)
	return null




